<template>
  <div class="form-table">
    <el-form ref="form" :model="form">
      <div class="formTable-title">
        <span></span>
        <span>{{ tableField.variableName }}</span>
      </div>
      <div class="formTable">
        <el-table
          size="mini"
          :stripe="true"
          :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
          style="width: 100%; overflow: hidden; display: grid"
          :data="tableData"
          :key="tableKey"
        >
          <el-table-column v-if="isEditable" label="" width="40">
            <template slot-scope="{ row }">
              <el-popconfirm v-if="row.new" title="确定要删除吗？" @confirm="handleDeleteRow(row)">
                <i class="el-icon-delete" slot="reference" />
              </el-popconfirm>
            </template>
          </el-table-column>

          <el-table-column
            v-for="(item, index) in columns"
            :prop="item.variable"
            :label="item.variableName"
            :key="index"
            :width="item.variableName === '序号' ? 60 : columns.length > 6 ? 'auto' : '160'"
            minWidth="160"
          >
            <template slot-scope="{ row }">
              <el-form-item :prop="handleKey(item.variable, row)">
                <div v-if="item.variable != 'SerialNumber'">
                  <fieldForm
                    v-model="form[handleKey(item.variable, row)]"
                    :table-field="item"
                    :table-status="tableStatus"
                    :birthmark="handleKey(item.variable, row)"
                    :embedded-table="embeddedTable"
                    :key="formKey"
                  />
                  <div v-if="tableStatus && tableStatus.isStatus === '1'" class="check-font">
                    {{ handleQueryContent(item.variable, row) }}
                  </div>
                </div>
                <div v-else class="serial-number">
                  {{ form[handleKey(item.variable, row)] }}
                </div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            minWidth="124"
            :width="columns.length > 6 ? randomWidth : 'auto'"
            :fixed="columns.length > 6 ? 'right' : null"
          >
            <template slot-scope="{ row }">
              <div :class="['form-tools', columns.length > 6 ? '' : 'form-tools-item']">
                <i
                  :class="[
                    'tool-note',
                    handleNotesStatus(row) === 1 ? 'el-icon-notebook-2' : 'el-icon-edit-outline',
                    handleNotesStatus(row) === '' ? 'colorDark' : '',
                  ]"
                  @click="handleNotes($event, row)"
                ></i>
                <div class="checkbox">
                  <el-checkbox
                    :disabled="
                      !tableStatus ||
                      tableStatus.isLapse !== '1' ||
                      tableStatus.isStatus === '1' ||
                      tableStatus.frozen !== '1' ||
                      !permissionController('pi::signature')
                    "
                    v-model="form[`$${tableField.embeddedTableKey}--${tableData.indexOf(row)}--sign`]"
                  />
                </div>
                <div v-for="(item, index) in handleTools()" :class="`tools-checkbox-${item.enable}`" :key="index">
                  <el-checkbox
                    :disabled="item.disabled || item.enable == 0"
                    v-model="form[`$${tableField.embeddedTableKey}--${tableData.indexOf(row)}--${item.tag}`]"
                  />
                </div>
                <div :class="`question question-${handleQuestionStatus(row)}`" @click="handleQuestion($event, row)">
                  &nbsp;
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="isEditable && !tableField.controlled" class="add-inner">
        <el-button icon="el-icon-plus" @click="addInner"></el-button>
      </div>
    </el-form>
    <el-dialog
      title="研究者批注"
      :visible.sync="dialogNotesVisible"
      :width="dataNotes && dataNotes.length > 0 ? '800px' : '500px'"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <notes
        size="mini"
        type="2"
        :table-status="tableStatus"
        :table-data="dataNotes"
        @close="handleCloseNotes"
        :exParams="exParams"
      />
    </el-dialog>
    <!-- 质疑列表 -->
    <el-dialog
      title="质疑列表"
      width="1000px"
      :visible.sync="dialogQueryVisible"
      :destroy-on-close="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeDialogQuestion"
    >
      <question
        :queryType="queryType"
        :ex-options="exOptions"
        :table-status="tableStatus"
        @create="createQuestion"
        :variableName="tableField.variableName"
        :dialogQuestionVisible="dialogQueryVisible"
        :queryListData="queryListData"
        style="height: 600px; overflow: auto"
      />
    </el-dialog>
    <!-- 增加质疑 -->
    <el-dialog
      title="增加质疑"
      :visible.sync="addQueryVisible"
      width="30%"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <add-question
        :queryType="queryType"
        :ex-options="exOptions"
        :table-status="tableStatus"
        :variableName="tableField.variableName"
        @callback="
          () => {
            addQueryVisible = false
            upgrade()
          }
        "
      />
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import fieldForm from './field-forms.vue'
import Notes from '../../notes.vue'
import Question from '../../question.vue'
import AddQuestion from '../../add-question.vue'
import { permissionController } from '@/utils/index'

export default {
  props: {
    value: {
      type: Object,
    },
    tableStatus: {
      type: Object,
    },
    tableField: {
      type: Object,
    },
    embeddedTable: {
      type: Array,
    },
    columns: {
      type: Array,
    },
    checkboxed: {
      type: Boolean,
    },
  },
  components: { fieldForm, AddQuestion, Question, Notes },
  data() {
    return {
      form: {},
      dialogNotesVisible: false,
      dataNotes: [],
      exParams: {},
      dialogQueryVisible: false,
      addQueryVisible: false,
      exOptions: {},
      tableData: null,
      tableKey: 0,
      isAdd: false,
      queryType: '1',
      queryListData: [],
      randomWidth: null,
      formKey: 0,
    }
  },
  computed: {
    ...mapState({
      subjectInfo: state => state.treatment.subjectInfo,
      audits: state => state.treatment.audits,
      visit: state => state.treatment.visit,
      relations: state => state.treatment.relations,
    }),
    ...mapGetters({
      findRole: 'treatment/findRole',
    }),
    isEditable() {
      return (
        this.permissionController('subject::ecrf::data::entery') &&
        this.tableField.embeddedTableType === '0' &&
        (!this.tableStatus || (this.tableStatus.isLapse === '1' && this.tableStatus.frozen === '1'))
      )
    },
  },
  watch: {
    form: {
      handler: function (val) {
        if (val) {
          this.$emit('input', val)
          // 表格变化要更新子组件 
          this.formKey += 1
        }
      },
      immediate: true,
      deep: true,
    },
    embeddedTable: {
      handler: function (val) {
        // 动态计算内嵌表右侧区域长度
        const list = this.audits.filter(item => item.status === 1)
        this.randomWidth = 105 + 25.5 * list.length
        // 更新内嵌表
        this.tableKey += 1
        //新增时修改序号
        if (val && val.length > 0) {
          val.forEach((item, index) => {
            if (item.new) {
              const { tableFieldList } = item
              tableFieldList.forEach(el => {
                if (el.variableName === '序号') {
                  el.variableValue = index + 1
                }
              })
            }
          })
          this.findTableData()
        }
      },
      immediate: true,
    },
    'tableField.embeddedTableKey': {
      handler: function (val) {
        this.findTableData()
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    permissionController,
    ...mapActions('eCRFDetail', ['annotationList', 'getQueryListAPI']),
    ...mapMutations({
      upgrade: 'treatment/upgrade',
    }),
    // 再次打开新增质疑
    createQuestion: function () {
      this.dialogQueryVisible = false
      this.addQueryVisible = true
    },
    // 打开质疑按钮
    async handleQuestion(e, row) {
      const classList = e.currentTarget.classList
      for (let v of classList.values()) {
        if (v && v.startsWith('question-')) {
          const arr = v.split('-')
          if (arr[1] <= 1) {
            return
          } else if (arr[1] >= 2 && arr[1] < 5) {
            // 接口放到外面
            const index = this.tableData.indexOf(row)
            const { tableFieldList } = this.embeddedTable[index]
            let params = { id: tableFieldList[1].formDataId }
            const res = await this.getQueryListAPI({ params })
            if (res.code === 200) {
              this.queryListData = res.data
              this.dialogQueryVisible = true
            }
          } else if (arr[1] >= 5) {
            if (this.tableStatus && this.tableStatus.isLapse === '1') {
              const index = this.tableData.indexOf(row)
              const { tableFieldList } = this.embeddedTable[index]
              tableFieldList.shift()
              this.exOptions = {
                tableFieldList,
              }
            }
            this.addQueryVisible = true
          }
        }
      }
    },
    // 关闭批注
    handleCloseNotes() {
      this.exParams = {}
      this.dataNotes = []
      this.dialogNotesVisible = false
    },
    handleNotes(e, row) {
      const classList = e.currentTarget.classList
      for (let v of classList.values()) {
        if (v == 'notes-') {
          return
        }
      }
      this.dataNotes.length = 0
      if (
        this.permissionController('crf::form::data::annotation') &&
        this.tableStatus &&
        this.tableStatus.isLapse === '1'
      ) {
        const index = this.tableData.indexOf(row)
        const { tableFieldList } = this.embeddedTable[index]
        const formVariableIds = tableFieldList[1].formFieldId
        const formId = tableFieldList[1].formDataId
        this.findNotes(formVariableIds, formId)
        this.exParams = {
          tableFieldList,
        }
      }
    },
    // 关闭质疑
    closeDialogQuestion() {
      this.dialogQuestionVisible = false
      this.upgrade()
    },

    findNotes(formVariableIds, formId) {
      this.dialogNotesVisible = true
      const params = {
        detailsId: formVariableIds,
        annotationType: '2',
        formId: formId,
      }
      this.annotationList({ params })
        .then(res => {
          const { code, data, message } = res
          if (code === 200) {
            this.dataNotes = data
            this.dialogNotesVisible = true
          } else {
            this.$message.error(message)
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    addInner() {
      this.isAdd = true
      this.$emit('add-inner', this.tableField.embeddedTableKey)
      setTimeout(this.findTableData)
    },
    handleDeleteRow(row) {
      if (this.tableData && this.tableData.length > 0) {
        const index = this.tableData.indexOf(row)
        this.$emit('delete', this.tableField.embeddedTableKey, index)
        this.findTableData()
      }
    },
    // 质疑内容
    handleQueryContent(variable, row) {
      if (this.tableData && this.tableData.length > 0) {
        const index = this.tableData.indexOf(row)
        const data = this.embeddedTable[index]
        if (data) {
          const { tableFieldList } = data
          if (tableFieldList && tableFieldList.length > 0) {
            const { questionContent } = tableFieldList.filter(tableField => tableField.variable == variable)[0]
            return questionContent ? questionContent : ''
          }
        }
      }
    },
    handleKey(variable, row) {
      if (this.tableData && this.tableData.length > 0) {
        const index = this.tableData.indexOf(row)
        return `${variable}--${index}`
      }
    },
    //处理表格数据
    findTableData() {
      this.form = {}
      this.tableData = null
      this.tableData =
        this.embeddedTable &&
        this.embeddedTable.map((e, i) => {
          const { tableFieldList, new: isNew } = e
          let craMax = -1
          let dmMax = -1
          let pmMax = -1
          let mmMax = -1
          let piMax = -1
          const obj = { new: isNew }
          tableFieldList.forEach(tableField => {
            const { variable, variableType, variableValue, defaultValue, cra, dm, pm, mm, pi } = tableField
            let value
            if (variableType === '20') {
              if (this.tableStatus) {
                if (variableValue) {
                  value = variableValue.split(',')
                } else {
                  value = []
                }
              } else {
                if (variableValue) {
                  value = variableValue.split(',')
                } else {
                  if (defaultValue) {
                    value = defaultValue.split(',')
                  } else {
                    value = []
                  }
                }
              }
            } else {
              if (this.tableStatus) {
                value = variableValue
              } else {
                if (variableValue) {
                  value = variableValue
                } else {
                  value = defaultValue || ''
                }
              }
            }
            obj[variable] = value
            this.$set(this.form, `${variable}--${i}`, value)
            if (this.checkboxed) {
              craMax = 2
              dmMax = 2
              pmMax = 2
              mmMax = 2
              piMax = 2
            } else {
              if (cra > craMax) craMax = cra
              if (dm > dmMax) dmMax = dm
              if (pm > pmMax) pmMax = pm
              if (mm > mmMax) mmMax = mm
              if (pi > piMax) piMax = pi
            }
          })

          this.handleAudits(i, 'cra', craMax === 2)
          this.handleAudits(i, 'dm', dmMax === 2)
          this.handleAudits(i, 'pm', pmMax === 2)
          this.handleAudits(i, 'mm', mmMax === 2)
          this.handleAudits(i, 'pi', piMax === 2)
          return obj
        })
    },
    // 权限控制
    handleAudits(index, keywords, checked) {
      if (keywords === 'pi') {
        this.$set(this.form, `$${this.tableField.embeddedTableKey}--${index}--sign`, checked)
      } else {
        const { code } = this.relations.filter(relation => relation.alias == keywords)[0]
        const target = this.audits.filter(audit => audit.roleCode == code)[0]
        if (target) {
          this.$set(this.form, `$${this.tableField.embeddedTableKey}--${index}--${target.tag}`, checked)
        }
      }
    },
    // 右侧按钮
    handleTools() {
      const result = []
      this.audits.forEach(audit => {
        const obj = {
          ...audit,
        }
        obj.disabled =
          audit.roleCode !== this.findRole ||
          !this.tableStatus ||
          this.tableStatus.isLapse === '2' ||
          this.tableStatus.isLapse === '3' ||
          this.tableStatus.isStatus === '1' ||
          this.tableStatus.frozen !== '1'
        obj.enable = this.converterMerge(audit)
        result.push(obj)
      })
      return result
    },
    converterMerge(audit) {
      let enable = this.columns
        .map(col => {
          const { fromDataChecksetupDTO } = col
          if (fromDataChecksetupDTO && Object.keys(fromDataChecksetupDTO).length > 0) {
            return parseInt(this.converter(audit, fromDataChecksetupDTO))
          } else {
            return 0
          }
        })
        .reduce((p, c) => p + c)
      if (enable > 0) {
        return 1
      } else {
        return 0
      }
    },
    converter(audit, fromDataChecksetupDTO) {
      if (!fromDataChecksetupDTO) {
        return '0'
      }
      let result
      const { checkSetupOne, checkSetupTwo, checkSetupThree, checkSetupFour, checkSetupFive } = fromDataChecksetupDTO
      switch (audit.sort) {
        case 1:
          result = checkSetupOne
          break
        case 2:
          result = checkSetupTwo
          break
        case 3:
          result = checkSetupThree
          break
        case 4:
          result = checkSetupFour
          break
        case 5:
          result = checkSetupFive
          break
      }
      return result
    },
    handleNotesStatus(row) {
      if (!this.permissionController('crf::form::data::annotation')) {
        return ''
      }
      if (this.tableStatus && this.tableStatus.isLapse === '1' && this.tableStatus.frozen === '1') {
        if (this.embeddedTable && this.embeddedTable.length > 0) {
          const index = this.tableData.indexOf(row)
          const data = this.embeddedTable[index]
          if (data && !data.new) {
            const { tableFieldList } = data
            if (tableFieldList && tableFieldList.length > 0) {
              const endorse = tableFieldList.map(tableField => tableField.endorse).reduce((p, c) => p + c)
              return endorse
            }
          }
        }
      } else {
        return ''
      }
    },
    // 判断质疑状态
    handleQuestionStatus(row) {
      let flag
      if (this.permissionController('send::challenge')) {
        flag = true
      }
      if (this.tableStatus) {
        if (this.tableStatus.isStatus === '1') {
          return 1
        }
        if (this.embeddedTable && this.embeddedTable.length > 0) {
          const index = this.tableData.indexOf(row)
          const data = this.embeddedTable[index]
          if (data && !data.new) {
            const { tableFieldList } = data
            let question = 0
            tableFieldList.forEach(tableField => {
              if (question === 0 || tableField.question > question) {
                question = tableField.question
              }
            })
            if (question == 1) {
              if (flag) {
                if (this.tableStatus.isLapse == '1' && this.tableStatus.frozen == '1') {
                  return 5
                } else {
                  return 1
                }
              }
            } else if (question == 2) {
              if (this.permissionController('send::challenge')) {
                return `${question}-2`
              } else {
                return `${question}-1`
              }
            }
            return question
          } else {
            return 1
          }
        } else {
          return 1
        }
      } else {
        return 1
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.form-table {
  padding: 1rem 0;
  .formTable-title {
    text-align: left;
    color: #303133;
    font-size: 0.875rem;
    font-weight: bold;
    line-height: 1.375rem;
    > span {
      &:first-child {
        display: inline-block;
        border: 2px solid #6b1685;
        border-radius: 15px;
        margin-right: 8px;
        height: 10px;
        float: left;
        margin-top: 5px;
      }
    }
  }
  .formTable {
    margin: 0.5rem 0;
    .el-icon-delete {
      font-size: 0.9375rem;
      color: #6b1685;
      cursor: pointer;
      &:hover {
        color: #f56c6c;
      }
    }

    .form-tools {
      flex: 1;
      display: flex;
      // line-height: 1rem;
      // justify-content: flex-end;
      padding-left: 7px;
      > div {
        margin-left: 0.75rem;
      }
      > .tool-note {
        margin-top: 7px;
        font-size: 16px;
        color: #753cca;
        cursor: pointer;
      }
      > .question {
        width: 0.9rem;
        height: 0.95rem;
        background-size: 0.9rem 0.9rem;
        background-repeat: no-repeat;
        margin-top: 6px;
        cursor: pointer;
      }
      // > .notes- {
      //   cursor: not-allowed;
      //   background-image: url("~@/assets/edc/case/jfcm07_01.png");
      // }

      // > .notes-0 {
      //   background-image: url("~@/assets/edc/case/jfcm07_02.png");
      // }

      // > .notes-1 {
      //   background-image: url("~@/assets/edc/case/jfcm07_03.png");
      // }
      > .question-0 {
        cursor: not-allowed;
        background-image: url('~@/assets/img/question-0.png');
      }

      > .question-1 {
        cursor: not-allowed;
        background-image: url('~@/assets/img/question-1.png');
      }

      > .question-2-1 {
        background-image: url('~@/assets/img/question-2-1.png');
      }

      > .question-2-2 {
        background-image: url('~@/assets/img/question-2-2.png');
      }

      > .question-3 {
        background-image: url('~@/assets/img/question-3.png');
      }

      > .question-4 {
        background-image: url('~@/assets/img/question-4.png');
      }

      > .question-5 {
        background-image: url('~@/assets/img/question-5.png');
      }
      .tools-checkbox-0 {
        /deep/ .el-checkbox__inner {
          background-size: 0.5rem;
          background-repeat: no-repeat;
          background-image: url('~@/assets/img/setup.png');
          background-position: center;
        }
      }
    }
    .form-tools-item {
      -webkit-box-pack: end;
      justify-content: end;
      padding-right: 9px;
    }
    .serial-number {
      font-size: 0.75rem;
    }
    .check-font {
      text-align: left;
      font-size: 0.75rem;
      color: #f56c6c;
    }
  }
  .formTable::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 0px; /*高宽分别对应横竖滚动条的尺寸*/
    scrollbar-arrow-color: red;
  }
  .formTable::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px rgb(215, 215, 215);
    box-shadow: inset 0 0 5px rgb(215, 215, 215);
    background: rgb(215, 215, 215);
    scrollbar-arrow-color: red;
  }
  .formTable::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(215, 215, 215, 0.2);
    box-shadow: inset 0 0 5px rgba(215, 215, 215, 0.2);
    border-radius: 0;
    background: rgba(215, 215, 215, 0.1);
  }
  /deep/ .el-table__body tr:hover > td {
    background-color: #e6ecff !important;
  }

  .add-inner {
    text-align: left;
    .el-button {
      padding: 0;
      width: 1.375rem;
      height: 1.375rem;
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
  /deep/ .el-form-item__content {
    line-height: normal;
  }
  .colorDark {
    color: #999 !important;
    cursor: not-allowed !important;
  }
}
</style>
